﻿using System;
using System.IO;
using System.Security.Permissions;
using Microsoft.Win32;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace InfoLeech
{
    public partial class ctlMachineTools : UserControl
    {
        private string connectionStringComputer = frmMain.connectionStringComputer;
        private BindingSource bindingSourceComputerHistory = new BindingSource();
        private SqlDataAdapter dataAdapterComputerHistory = new SqlDataAdapter();
        private DataTable tableComputerHistory = new DataTable();

        public ctlMachineTools()
        {
            InitializeComponent();
            // Create toolstrip
            System.Windows.Forms.ToolTip ToolTipInstalledApps = new System.Windows.Forms.ToolTip();
            ToolTipInstalledApps.SetToolTip(this.tbComputer, "Laat dit veld leeg voor local computer.\n" + 
                "Voor remote computer moet je InfoLeech uitvoeren met verhoogde rechten.");

            // Bind the DataGridView to the BindingSource
            dataGridViewComputerHistory.DataSource = bindingSourceComputerHistory;
        }

        private void btnSearchInstalledApps_Click(object sender, EventArgs e)
        {
            getInstalledApps();
        }

        private void getInstalledApps()
        {
            string computerName;
            //tableInstalledApps.Clear();
            //Create datatable and add columns.
            DataTable tableInstalledApps = new DataTable();
            DataColumn nameColumn = new DataColumn("Name", typeof(string));
            DataColumn versionColumn = new DataColumn("Version", typeof(string));
            DataColumn installSourceColumn = new DataColumn("Install Source", typeof(string));
            tableInstalledApps.Columns.AddRange(new DataColumn[] { nameColumn, versionColumn, installSourceColumn });

            // Check for computername.
            if (tbComputer.Text.Length == 0)
            {
                computerName = String.Empty;
            }
            else
            {
                computerName = tbComputer.Text;
            }

            try
            {
                // Open HKEY_Local_Machine\Environment 
                string SoftwareKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
                using (RegistryKey rk = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, computerName).OpenSubKey(SoftwareKey))
                {
                    //Let's go through the registry keys and get the info we need:
                    foreach (string skName in rk.GetSubKeyNames())
                    {
                        using (RegistryKey sk = rk.OpenSubKey(skName))
                        {
                            try
                            {
                                //If the key has value, continue, if not, skip it:
                                if (!(sk.GetValue("DisplayName") == null))
                                {
                                    //Is the install location known?
                                    DataRow rw = tableInstalledApps.NewRow();
                                    rw[nameColumn] = sk.GetValue("DisplayName").ToString();
                                    rw[versionColumn] = sk.GetValue("DisplayVersion");
                                    rw[installSourceColumn] = "";
                                    tableInstalledApps.Rows.Add(rw);
                                    if (sk.GetValue("InstallSource") == null)
                                        rw[installSourceColumn] = "";
                                    else
                                        rw[installSourceColumn] = sk.GetValue("InstallSource");
                                }
                            }
                            catch (Exception e)
                            {
                                MessageBox.Show(e.Message);
                            }
                        }
                    }
                }
            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message);
            }

            // Create new table with only distinct values
            DataTable distinctInstalledApps = tableInstalledApps.DefaultView.ToTable( /*distinct*/ true);
            //Clear original table
            tableInstalledApps.Clear();
            // set the grid's data source
            dataGridViewInstalledApps.DataSource = distinctInstalledApps;
        }

        private void GetComputerHistoryData()
        {
            if (tbComputerHistory.Text.Length < 3)
            {
                MessageBox.Show("Zoekstring is te kort. Deze moet minimaal 3 karakters lang zijn.");
            }
            else
            {
                //Clear table
                try
                {
                    tableComputerHistory.Clear();
                }
                catch (DataException e)
                {
                    // Process exception and return.
                    System.Diagnostics.EventLog log = new System.Diagnostics.EventLog();
                    log.Source = "infoLeech";
                    log.WriteEntry(e.ToString());
                }

                try
                {
                    string qryLogonHistory =
                        "select RTRIM(computername) Computername, RTRIM(username) Account, RTRIM(userdescription) Username, " 
                        + "RTRIM(datum) Date, RTRIM(timebegin) StartTime from userlogging where computername LIKE '%"
                        + tbComputerHistory.Text + "%' order by Datum desc";

                    // Create a new data adapter based on the specified query.
                    dataAdapterComputerHistory = new SqlDataAdapter(qryLogonHistory, connectionStringComputer);
                    tableComputerHistory.Locale = System.Globalization.CultureInfo.InvariantCulture;

                    //Fill datatable with query results.
                    dataAdapterComputerHistory.Fill(tableComputerHistory);
                    bindingSourceComputerHistory.DataSource = tableComputerHistory;
                }
                catch (SqlException)
                {
                    MessageBox.Show("Error connecting to database.");
                }
            }
        }

        private void tbComputer_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {
                getInstalledApps();
            }
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // The context menu strip called this method, so we need to determine which DGV it was clicked on    
            ToolStripDropDownItem item = sender as ToolStripDropDownItem;
            if (item == null) // Error            
                return;
            ContextMenuStrip strip = item.Owner as ContextMenuStrip;
            DataGridView grid = strip.SourceControl as DataGridView;
            if (grid == null) // Control wasn't a DGV
                return;
            DataObject data = grid.GetClipboardContent();
            if (data != null)
                Clipboard.SetDataObject(data);
        }

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // The context menu strip called this method, so we need to determine which DGV it was clicked on    
            ToolStripDropDownItem item = sender as ToolStripDropDownItem;
            if (item == null) // Error            
                return;
            ContextMenuStrip strip = item.Owner as ContextMenuStrip;
            DataGridView grid = strip.SourceControl as DataGridView;
            if (grid == null) // Control wasn't a DGV
                return;
            grid.SelectAll();
        }

        private void btnSearchComputerHistory_Click(object sender, EventArgs e)
        {
            GetComputerHistoryData();
        }

        private void tbComputerHistory_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {
                GetComputerHistoryData();
            }
        }
    }
 }